package com.ybkj.daijia.server.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.config.PassengerApi;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.mapper.DriverPaymentsRecordMapper;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverLogin;
import com.ybkj.daijia.server.model.DriverRebatePaymentRecord;
import com.ybkj.daijia.server.service.DriverLoginService;
import com.ybkj.daijia.server.service.DriverRebatePaymentRecordService;
import com.ybkj.daijia.server.service.DriverService;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author zhyu
 * @date
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@Controller
@RequestMapping("driver")
public class DriverRebatePaymentRecordController {

    private Logger logger = LoggerFactory.getLogger(DriverRebatePaymentRecordController.class);

    @Autowired
    private DriverService driverService;

    @Autowired
    private DriverLoginService driverLoginService;

    @Autowired
    private DriverRebatePaymentRecordService driverRebatePaymentRecordService;
    @Autowired
    private PassengerApi passengerApi;
    @Autowired
    private DriverPaymentsRecordMapper driverPaymentsRecordMapper;

    /***
     *  后台获取司机推荐奖励明细
     * @param id
     * @param startTime
     * @param endTime
     * @return
     */
    @RequestMapping(value = "extendDetail/{id}", method = RequestMethod.GET)
    public ModelAndView rebateMoney(@PathVariable("id") Long id,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime) {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("drivermoneyview")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("driver/extendDetail");

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String now = formatter.format(new Date());
            Date start = null;
            Date end = null;
            try {
                if (StringUtils.isEmpty(endTime)) {
                    Calendar cl = Calendar.getInstance();
                    cl.setTime(DateUtils.parseDate(now, "yyyy-MM-dd"));
                    cl.add(Calendar.HOUR_OF_DAY, 23);
                    cl.add(Calendar.MINUTE, 59);
                    cl.add(Calendar.SECOND, 59);
                    end = cl.getTime();
                } else {
                    Calendar cl = Calendar.getInstance();
                    cl.setTime(DateUtils.parseDate(endTime, "yyyy-MM-dd"));
                    cl.add(Calendar.HOUR_OF_DAY, 23);
                    cl.add(Calendar.MINUTE, 59);
                    cl.add(Calendar.SECOND, 59);
                    end = cl.getTime();
                }

                if (StringUtils.isEmpty(startTime)) {
                    Calendar cl = Calendar.getInstance();
                    cl.setTime(DateUtils.parseDate(now, "yyyy-MM-dd"));
                    cl.add(Calendar.MONTH, -1);
                    start = cl.getTime();
                } else {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }

            mv.addObject("start", start);
            mv.addObject("end", end);
            mv.addObject("driver", driverService.findOne(id));
            mv.addObject("page",
                driverRebatePaymentRecordService.queryByEmploy(id, null, start, end,
                    Pager.getPage(), Pager.getLimit()));

            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    /***
     * 返回移动端司机推荐奖励明细
     * @param employToken
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping(value = "queryDriverRebate", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport queryDriverRebate(String employToken, Integer page, Integer limit) {
        logger.debug("employToken:{},page:{},limit:{}", employToken, page, limit);
        Driver driver;
        if (!"super".equals(employToken)) {
            if (StringUtils.isBlank(employToken) || null == page || null == limit) {
                return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
            }

            DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

            if (null == driverLogin) {
                return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
            }

            if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
                return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
            }
            driver = driverService.findOne(driverLogin.getDriverId());
        } else {
            driver = driverService.findOne(30L);
        }

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        try {

            Page<DriverRebatePaymentRecord> rebatePage = driverRebatePaymentRecordService
                .queryByEmploy(driver.getId(), null, null, null, page, limit);

            List<DriverRebatePaymentRecord> content = rebatePage.getContent();
            long totalElements = rebatePage.getTotalElements();
            Map<Long, DriverRebatePaymentRecord> ids = new HashMap<>();
//            List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
            List<DriverRebatePaymentRecord> mapList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(content)) {
                for (DriverRebatePaymentRecord driverPaymentsRecord : content) {
                    mapList.add(driverPaymentsRecord);

                    if (null != driverPaymentsRecord.getPassengerId()) {
                        ids.put(driverPaymentsRecord.getPassengerId(), driverPaymentsRecord);
                    }
                }
            }
            //添加补充信息
            if (0 != ids.size()) {
                JSONArray wxInfos = passengerApi.getWxInfo(ids.keySet());
                if (null != wxInfos) {
                    for (int i = 0; i < wxInfos.size(); i++) {
                        JSONObject obj = wxInfos.getJSONObject(i);
                        Long id = obj.getLong("id");
                        String wxNickName = obj.getString("wxNickName");
                        String wxHeadImgUrl = obj.getString("wxHeadImgUrl");
                        DriverRebatePaymentRecord driverRebatePaymentRecord = ids.get(id);
                        if (null != driverRebatePaymentRecord) {
                            driverRebatePaymentRecord.setWxHeadImgUrl(wxHeadImgUrl);
                            driverRebatePaymentRecord.setWxNickName(wxNickName);
                        }
                    }
                }
            }

            Pageable pageable = new PageRequest(page, limit);
//            Page<Map<String, Object>> pageMap = new PageImpl<Map<String, Object>>(mapList, pageable, totalElements);
            Page<DriverRebatePaymentRecord> pageMap = new PageImpl<DriverRebatePaymentRecord>(
                mapList, pageable, totalElements);
            Long count = passengerApi.countPassengerByIntroducer(driver.getUsername(), null, 1);
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("page", pageMap);
            dataMap.put("totalMoney", driver.getRebateMoney());
            if (null != count) {
                dataMap.put("count", count);
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(dataMap);
            return instance;

        } catch (Exception e) {
            logger.error("api v4 driver queryRebate error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

}
